<template>
  <div class="dish-container">
    <!-- 头部操作区域 -->
    <el-card class="header-card">
      <div class="header-operation">
        <el-select
          v-model="statusFilter"
          placeholder="状态"
          @change="handleFilter"
          style="width: 80px; margin-left: 10px"
        >
          <el-option label="全部" value="" />
          <el-option label="上架" value="1" />
          <el-option label="下架" value="0" />
        </el-select>
        <el-select
          v-model="typeFilter"
          placeholder="类型"
          @change="handleFilter"
          style="width: 80px; margin-left: 10px"
        >
          <el-option label="全部" value="" />
          <el-option label="冷饮" value="冷饮" />
          <el-option label="热饮" value="热饮" />
          <el-option label="冰淇淋" value="冰淇淋" />
        </el-select>
        <el-input
          v-model="searchKeyword"
          placeholder="搜索菜品名称"
          @keyup.enter="handleFilter"
          clearable
          style="width: 240px; margin-left: 10px"
        >
          <template #suffix>
            <el-icon class="el-input__icon" @click="handleFilter">
              <Search />
            </el-icon>
          </template>
        </el-input>
      </div>
    </el-card>

    <!-- 菜品列表 -->
    <el-card class="table-card">
      <el-table
        :data="tableData"
        border
        stripe
        style="width: 100%"
      >
        <el-table-column type="index" label="序号" width="80" align="center" />
        <el-table-column prop="name" label="名称" min-width="150" />
        
        <!-- 价格列 -->
        <el-table-column prop="rmb" label="价格" width="100" align="right">
          <template #default="scope">
            {{ scope.row.rmb }} 元
          </template>
        </el-table-column>
        
        <el-table-column prop="type" label="类型" width="100" />
        <el-table-column prop="beizhu" label="备注" min-width="150" />
        <el-table-column label="状态" width="100" align="center">
          <template #default="scope">
            <el-tag :type="scope.row.status === 1 ? 'success' : 'danger'">
              {{ scope.row.status === 1 ? '上架' : '下架' }}
            </el-tag>
          </template>
        </el-table-column>
        
        <!-- 新增操作列 -->
        <el-table-column label="操作" width="120" align="center">
          <template #default="scope">
            <el-button 
              type="primary" 
              size="mini"
              @click="openCartDialog(scope.row)"
            >
              加入购物车
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页组件 -->
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="currentPage"
        :page-sizes="[10, 20, 50, 100]"
        :page-size="pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        style="margin-top: 20px; text-align: right"
      />
    </el-card>
  </div>

  <!-- 加入购物车对话框 -->
  <el-dialog 
    v-model="cartDialogVisible" 
    title="选择规格" 
    width="300px"
  >
    <el-form :model="cartForm" label-width="80px">
      <el-form-item label="数量">
        <el-input-number 
          v-model="cartForm.count" 
          :min="1" 
          :max="10" 
          :step="1"
        />
      </el-form-item>
      <el-form-item label="糖度">
        <el-select v-model="cartForm.sugar" placeholder="请选择糖度">
          <el-option label="正常糖" value="normal" />
          <el-option label="少糖" value="less" />
          <el-option label="半糖" value="half" />
          <el-option label="微糖" value="micro" />
          <el-option label="无糖" value="none" />
        </el-select>
      </el-form-item>
      <el-form-item label="温度">
        <el-select v-model="cartForm.temp" placeholder="请选择温度">
          <el-option label="常温" value="normal" />
          <el-option label="冷" value="cold" />
          <el-option label="热" value="hot" />
        </el-select>
      </el-form-item>
      <el-form-item label="小料">
        <el-select v-model="cartForm.topping" multiple placeholder="请选择小料">
          <el-option label="珍珠" value="pearl" />
          <el-option label="波霸" value="boba" />
          <el-option label="椰果" value="coconut" />
          <el-option label="布丁" value="pudding" />
          <el-option label="仙草" value="grass" />
        </el-select>
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="cartDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="addToCart">确认加入</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import axios from 'axios'
import { Search } from '@element-plus/icons-vue'
import { useRouter } from 'vue-router'

// 状态管理
const tableData = ref([])
const total = ref(0)
const currentPage = ref(1)
const pageSize = ref(10)
const statusFilter = ref('')
const typeFilter = ref('')
const searchKeyword = ref('')

// 购物车对话框状态
const cartDialogVisible = ref(false)
const cartForm = reactive({
  count: 1,
  sugar: '',
  temp: '',
  topping: []
})
const currentDish = ref({}) // 当前操作的菜品
const router = useRouter()

// 生命周期
onMounted(() => {
  fetchTableData()
})

// 获取列表数据
const fetchTableData = async () => {
  try {
    let response = null
    if (searchKeyword.value) {
      response = await axios.get('/api/tea/search/name', {
        params: { name: searchKeyword.value }
      })
    } else if (statusFilter.value !== '') {
      response = await axios.get('/api/tea/search/status', {
        params: { status: statusFilter.value }
      })
    } else if (typeFilter.value !== '') {
      response = await axios.get('/api/tea/search/type', {
        params: { type: typeFilter.value }
      })
    } else {
      response = await axios.get('/api/tea/getAll')
    }
    tableData.value = response.data.data || []
    total.value = tableData.value.length
  } catch (error) {
    console.error('获取数据失败:', error)
    ElMessage.error('获取数据失败')
  }
}

// 筛选处理
const handleFilter = () => {
  currentPage.value = 1
  fetchTableData()
}

// 分页处理
const handleSizeChange = (val) => {
  pageSize.value = val
  currentPage.value = 1
  fetchTableData()
}

const handleCurrentChange = (val) => {
  currentPage.value = val
  fetchTableData()
}

// 打开购物车对话框
const openCartDialog = (row) => {
  if (row.status !== 1) {
    ElMessage.warning('该菜品已下架，无法加入购物车')
    return
  }
  currentDish.value = row
  // 重置表单
  cartForm.count = 1
  cartForm.sugar = ''
  cartForm.temp = ''
  cartForm.topping = []
  cartDialogVisible.value = true
}

// 加入购物车并通过路由传递数据
const addToCart = () => {
  if (!cartForm.sugar || !cartForm.temp) {
    ElMessage.warning('请选择糖度和温度')
    return
  }
  
  // 构造购物车商品数据
  const cartItem = {
    id: currentDish.value.id,
    name: currentDish.value.name,
    price: currentDish.value.rmb,
    count: cartForm.count,
    sugar: cartForm.sugar,
    temp: cartForm.temp,
    topping: cartForm.topping,
    spec: getSpecText() // 规格描述
  }
  
  // 通过路由状态传递商品数据
  router.push({
    path: '/cart',
    state: {
      addedItem: cartItem,
      isNewAdd: true // 标记是否为新增商品
    }
  })
  
  cartDialogVisible.value = false
  ElMessage.success('已加入购物车')
}

// 获取规格描述文本
const getSpecText = () => {
  const sugarMap = {
    normal: '正常糖',
    less: '少糖',
    half: '半糖',
    micro: '微糖',
    none: '无糖'
  }
  
  const tempMap = {
    normal: '常温',
    cold: '冷',
    hot: '热'
  }
  
  const toppingMap = {
    pearl: '珍珠',
    boba: '波霸',
    coconut: '椰果',
    pudding: '布丁',
    grass: '仙草'
  }
  
  let spec = `${sugarMap[cartForm.sugar]} ${tempMap[cartForm.temp]}`
  if (cartForm.topping.length > 0) {
    spec += ` + ${cartForm.topping.map(t => toppingMap[t]).join('、')}`
  }
  return spec
}
</script>

<style scoped>
.dish-container {
  padding: 20px;
}

.header-card {
  margin-bottom: 20px;
}

.header-operation {
  display: flex;
  align-items: center;
}

.table-card {
  padding: 20px;
}

.el-pagination {
  margin-top: 20px;
  text-align: right;
}
</style>